package com.example.dingdong.service.impl;
 
import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.example.dingdong.model.domain.Order;
import com.example.dingdong.service.OrderManager;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;
/**
 * 邮箱信息的发送
 */

@Service
public class SimpleOrderManager implements OrderManager {

    @Value("${mail.address}")
    private String sendAddress;

    @Autowired
    private JavaMailSender mailSender;      //用于发送邮件

    /**
     * 设置 JavaMailSender 的方法
     * @param mailSender 用于发送邮件的 JavaMailSender 实例
     */
    public void setMailSender(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    /**
     * 发送包含密码的邮件
     * @param order 包含用户信息的订单对象
     * @param reciveAddress 收件人的电子邮件地址
     */
    public void sendPassword(Order order, String reciveAddress) {
        // 创建 MimeMessagePreparator 对象，用于准备 MimeMessage
        MimeMessagePreparator preparator = new MimeMessagePreparator() {
            public void prepare(@NotNull MimeMessage mimeMessage) throws Exception {
                // 设置邮件的收件人
                mimeMessage.setRecipient(Message.RecipientType.TO,
                        new InternetAddress(reciveAddress));
                // 设置邮件的发件人
                mimeMessage.setFrom(new InternetAddress(sendAddress));
                // 设置邮件的内容
                mimeMessage.setText("亲爱的 " + order.getName() + "\n" +
                        "欢迎使用叮咚在线音乐平台，您的密码是 :" + order.getPassword() + "。");
            }
        };

        try {
            // 发送准备好的邮件
            this.mailSender.send(preparator);
        } catch (MailException ex) {
            // 捕获邮件发送异常，并打印错误信息
            System.err.println(ex.getMessage());
        }
    }

    /**
     * 发送包含验证码的邮件
     * @param code 要发送的验证码
     * @param reciveAddress 收件人的电子邮件地址
     */
    public void sendCode(String code, String reciveAddress) {
        // 创建 MimeMessagePreparator 对象，用于准备 MimeMessage
        MimeMessagePreparator preparator = new MimeMessagePreparator() {
            public void prepare(@NotNull MimeMessage mimeMessage) throws Exception {
                // 设置邮件的收件人
                mimeMessage.setRecipient(Message.RecipientType.TO,
                        new InternetAddress(reciveAddress));
                // 设置邮件的发件人
                mimeMessage.setFrom(new InternetAddress(sendAddress));
                // 设置邮件的内容
                mimeMessage.setText("欢迎使用叮咚在线音乐平台，您的验证码是： " + code);
            }
        };
        // 发送准备好的邮件
        this.mailSender.send(preparator);
    }
}